package com.csiec.clock.view.model;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.baidu.mapapi.map.MapPoi;
import com.csiec.clock.R;
import com.csiec.clock.bean.Clock;
import com.csiec.clock.bean.PositionInformation;
import com.csiec.clock.bean.result.ResultCode;
import com.csiec.clock.callback.NewClockCallBack;
import com.csiec.clock.databinding.NewFragmentBinding;
import com.csiec.clock.map.BaiDuMapActivity;
import com.csiec.clock.model.NewModel;
import com.csiec.clock.utils.FileUtil;
import com.github.gzuliyujiang.calendarpicker.CalendarPicker;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButtonDrawable;

import java.text.SimpleDateFormat;
import java.util.Date;

public class NewViewModel extends ViewModel {
    static NewViewModel newViewModel;
    @SuppressLint("StaticFieldLeak")
    private Activity activity;
    private NewFragmentBinding binding;
    private final String TAG = "NewViewModel";
    int checkIndex1 = 0;
    int checkIndex2 = 0;
    int checkIndex3 = 0;
    long first_time = 0;
    long end_time = 0;

    final String[] typeStrs = new String[]{"单次打卡", "多次打卡"};
    final String[] spaceStrs = new String[]{"用户位置", "固定位置"};
    final String[] mustStrs = new String[]{"非必填", "必填"};
    final String[] notRequired = new String[]{"姓名", "体温", "手机号", "班级", "备注", "专业"};
    final String[] required = new String[]{"*姓名", "*体温", "*手机号", "*班级", "*备注", "*专业"};

    private MutableLiveData<String> showText;
    private MutableLiveData<String> spaceText;
    private MutableLiveData<String> timeStart;
    private MutableLiveData<String> timeEnd;
    private MutableLiveData<Boolean> openSpace;
    private MutableLiveData<MapPoi> mapPoi;
    private MutableLiveData<String> title;
    private MutableLiveData<String> address;
    private MutableLiveData<String> position;
    private MutableLiveData<String> range;
    private MutableLiveData<String> latitude; //经度
    private MutableLiveData<String> longitude;//纬度


    private final Handler handler = new Handler();

    private NewModel model;

    public static NewViewModel getNewViewModel() {
        if (newViewModel == null) {
            newViewModel = new NewViewModel();
        }
        return newViewModel;
    }

    public void init(Activity activity, NewFragmentBinding binding) {
        this.activity = activity;
        this.binding = binding;
        model = new NewModel();
        if (showText == null) {
            showText = new MutableLiveData<>();
            showText.setValue("单次打卡");
        }
        if (spaceText == null) {
            spaceText = new MutableLiveData<>();
            spaceText.setValue("用户位置");
        }
        if (timeStart == null) {
            timeStart = new MutableLiveData<>();
        }
        if (timeEnd == null) {
            timeEnd = new MutableLiveData<>();
        }
        if (mapPoi == null) {
            mapPoi = new MutableLiveData<>();
        }
        if (address == null) {
            address = new MutableLiveData<>();
            address.setValue("");
        }
        if (position == null) {
            position = new MutableLiveData<>();
        }
        if (title == null) {
            title = new MutableLiveData<>();
        }
        if (range == null) {
            range = new MutableLiveData<>();
        }
        if (latitude == null) {
            latitude = new MutableLiveData<>();
        }
        if (longitude == null) {
            longitude = new MutableLiveData<>();
        }
        if (openSpace == null) {
            openSpace = new MutableLiveData<>();
            openSpace.setValue(false);
        }
    }


    //选择打卡类型
    public void selectType() {
        new QMUIDialog.CheckableDialogBuilder(activity)
                .addItems(typeStrs, (dialog, which) -> {
                    Toast.makeText(activity, typeStrs[which], Toast.LENGTH_SHORT).show();
                    checkIndex1 = which;
                    showText.setValue(typeStrs[which]);
                    dialog.dismiss();
                })
                .setCheckedIndex(checkIndex1)
                .show();
    }

    //选择打卡位置
    public void selectSpace() {
        if (openSpace.getValue()) {
            new QMUIDialog.CheckableDialogBuilder(activity)
                    .addItems(spaceStrs, (dialog, which) -> {
                        Toast.makeText(activity, spaceStrs[which], Toast.LENGTH_SHORT).show();
                        checkIndex3 = which;
                        spaceText.setValue(spaceStrs[which]);
                        if (which == 1) {
                            //选择位置
                            Intent intent = new Intent(activity, BaiDuMapActivity.class);
                            activity.startActivity(intent);
                        }
                        dialog.dismiss();
                    })
                    .setCheckedIndex(checkIndex3)
                    .show();
        }
    }

    //选择必填项
    @SuppressLint("ResourceAsColor")
    public void selectMust(int index) {
        new QMUIDialog.CheckableDialogBuilder(activity)
                .addItems(mustStrs, (dialog, which) -> {
                    Toast.makeText(activity, mustStrs[which], Toast.LENGTH_SHORT).show();
                    checkIndex2 = which;
                    switch (index) {
                        case 1:
                            changeRequired(index, which, binding.nameBtn);
                            break;
                        case 2:
                            changeRequired(index, which, binding.temperatureBtn);
                            break;
                        case 3:
                            changeRequired(index, which, binding.phoneBtn);
                            break;
                        case 4:
                            changeRequired(index, which, binding.classBtn);
                            break;
                        case 5:
                            changeRequired(index, which, binding.remarksBtn);
                            break;
                        case 6:
                            changeRequired(index, which, binding.majorBtn);
                            break;
                    }
                    dialog.dismiss();
                })
                .show();
    }

    //改变必选与非必选
    private void changeRequired(int index, int which, QMUIRoundButton qmuiRoundButton) {
        if (which == 1) {
            PositionInformation.getPositionInformation()[index - 1].setClick(true);
            qmuiRoundButton.setText(required[index - 1]);
            setBgColorForQMUIRB(qmuiRoundButton, R.color.qmui_config_color_red);
        } else {
            PositionInformation.getPositionInformation()[index - 1].setClick(false);
            qmuiRoundButton.setText(notRequired[index - 1]);
            setBgColorForQMUIRB(qmuiRoundButton, R.color.qmui_btn_blue_text);
        }

    }

    /**
     * 设置qmui背景色
     *
     * @param qmuiRoundButton
     * @param color
     */
    private void setBgColorForQMUIRB(QMUIRoundButton qmuiRoundButton, int color) {
        QMUIRoundButtonDrawable qmuiRoundButtonDrawable = (QMUIRoundButtonDrawable) qmuiRoundButton.getBackground();
        ColorStateList colorStateList = ColorStateList.valueOf(activity.getResources().getColor(color));
        qmuiRoundButtonDrawable.setStrokeColors(colorStateList);
    }

    private String changeTime(long data) {
        Date resDate = new Date(data);
        @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.format(resDate);
    }

    //选择开始时间
    public void selectStartTime() {
        CalendarPicker picker = new CalendarPicker(activity);
        picker.setRangeDateOnFuture(3);
        picker.setOnSingleDatePickListener(date -> {
            if (first_time == 0) {
                first_time = System.currentTimeMillis();
            }
            picker.setSelectedDate(first_time);
            first_time = date.getTime();
            if (end_time != 0) {
                if (end_time <= first_time) {
                    showTip(QMUITipDialog.Builder.ICON_TYPE_INFO, "结束日期不能小于开始日期");
                } else {
                    timeStart.setValue(changeTime(first_time));
                }
            } else {
                timeStart.setValue(changeTime(first_time));
            }
        });
        picker.show();
    }

    //选择结束时间
    public void selectEndTime() {
        CalendarPicker picker = new CalendarPicker(activity);
        picker.setRangeDateOnFuture(3);
        picker.setOnSingleDatePickListener(date -> {
            if (first_time == 0) {
                showTip(QMUITipDialog.Builder.ICON_TYPE_INFO, "请先选择开始时间");
            } else {
                end_time = date.getTime();
                if (end_time <= first_time) {
                    showTip(QMUITipDialog.Builder.ICON_TYPE_INFO, "结束日期不能小于开始日期");
                } else {
                    timeEnd.setValue(changeTime(end_time));
                }
            }
        });
        picker.show();
    }

    Clock clock;

    //新建打卡
    public void newClock() {
        clock = new Clock();
        if (title.getValue() == null) {
            showTip(QMUITipDialog.Builder.ICON_TYPE_FAIL, "请输入标题");
            return;
        }
        if (timeStart.getValue() == null) {
            showTip(QMUITipDialog.Builder.ICON_TYPE_FAIL, "请选择开始时间");
            return;
        }
        if (timeEnd.getValue() == null) {
            showTip(QMUITipDialog.Builder.ICON_TYPE_FAIL, "请选择结束时间");
            return;
        }

        Log.d(TAG, "newClock: " + title.getValue());

        clock.setTitle(title.getValue());
        clock.setStartDate(timeStart.getValue());
        clock.setEndDate(timeEnd.getValue());
        clock.setStartTime("08:01");
        clock.setEndTime("23:59");
        clock.setType(String.valueOf(checkIndex1));
        clock.setPositionType(spaceText.getValue());
        clock.setRange(range.getValue());

        clock.setAddress(address.getValue());
        clock.setLatitude(latitude.getValue());
        clock.setLongitude(longitude.getValue());
        //如果开启了定位
        if ("".equals(address.getValue())) {
            clock.setAddress("用户位置");
            clock.setLatitude("0.0");
            clock.setLongitude("0.0");
            clock.setRange("500");
        }
        clock.setDestination(String.valueOf(openSpace.getValue()));
        clock.setInformation_type("true");
        clock.setPositionInformation(PositionInformation.getRequired());

        model.newClock(clock, new NewClockCallBack() {
            @Override
            public void onSuccess(ResultCode backData) {
                if (backData.getStatus() == 200) {
                    handler.post(() -> {
                        FileUtil.copyText(activity, backData.getData().getCode());
                        showTip(QMUITipDialog.Builder.ICON_TYPE_SUCCESS, "创建成功,已将分享码复制到剪贴板");
                        clearForm();
                    });
                } else {
                    handler.post(() -> {
                        showTip(QMUITipDialog.Builder.ICON_TYPE_SUCCESS, "创建失败");
                    });
                }
            }

            @Override
            public void onFailed() {
                handler.post(() -> {
                    showTip(QMUITipDialog.Builder.ICON_TYPE_FAIL, "网络异常");
                });
            }
        });

    }

    public void clearForm() {
        clock = null;
        final QMUIRoundButton[] btnList = new QMUIRoundButton[]{binding.nameBtn, binding.temperatureBtn, binding.phoneBtn, binding.classBtn, binding.remarksBtn, binding.majorBtn,};
        showText.setValue("单次打卡");
        timeEnd.setValue(null);
        timeStart.setValue(null);
        title.setValue(null);
        spaceText.setValue("用户位置");
        openSpace.setValue(false);
        latitude.setValue(null);
        longitude.setValue(null);
        range.setValue("");
        address.setValue("");
        position.setValue(null);
        for (int i = 0; i < 6; i++) {
            PositionInformation.getPositionInformation()[i].setClick(false);
            btnList[i].setText(notRequired[i]);
            setBgColorForQMUIRB(btnList[i], R.color.qmui_btn_blue_text);
        }
    }

    //提示悬浮窗
    public void showTip(int type, String msg) {
        QMUITipDialog tipDialog = new QMUITipDialog.Builder(activity)
                .setIconType(type)
                .setTipWord(msg)
                .create();
        tipDialog.show();
        binding.tvTermText.postDelayed(tipDialog::dismiss, 2000);
    }


    public MutableLiveData<String> getShowText() {
        return showText;
    }

    public MutableLiveData<String> getTimeStart() {
        return timeStart;
    }

    public MutableLiveData<String> getTimeEnd() {
        return timeEnd;
    }

    public MutableLiveData<String> getSpaceText() {
        return spaceText;
    }

    public MutableLiveData<Boolean> getOpenSpace() {
        return openSpace;
    }

    public MutableLiveData<String> getTitle() {
        return title;
    }

    public MutableLiveData<String> getPosition() {
        return position;
    }

    public MutableLiveData<String> getAddress() {
        return address;
    }

    public MutableLiveData<String> getRange() {
        return range;
    }

    public MutableLiveData<String> getLatitude() {
        return latitude;
    }

    public MutableLiveData<String> getLongitude() {
        return longitude;
    }
}